<template>
  <div v-loading="loading" background="#ffffff00" class="container_warp">
    <div id="containerChart" />
    <RightDrawer class="right_drawer" :drawer-type="type" :select-cell="selectCell" :graph="graph" :grid="grid" @deleteNode="deleteNode" />
    <div class="operating">
      <div class="btn-group" style="margin-left: -21px">
        <div class="btn nodeCss" :title="'GP'" style="border: 1px solid #DB8E8E;background: #DB8E8E !important;margin-left:0" @click="startDrag('Rect',$event,$t('私募基金'),'#DB8E8E')">
          GP
        </div>
        <div class="btn nodeCss" :title="'LP'" style="border: 1px solid #91B5C3;background: #91B5C3 !important;" @click="startDrag('Rect',$event,$t('其他股东'),'#91B5C3')">
          LP
        </div>
        <div class="btn nodeCss" :title="$t('公司')" style="border: 1px solid #E26A6A;background: #E26A6A !important;" @click="startDrag('Rect',$event,$t('平台公司'),'#E26A6A')">
          {{ $t('公司') }}
        </div>
        <div class="btn nodeCss" :title="$t('基金')" style="border: 1px solid #678F9E;background: #678F9E !important;" @click="startDrag('Rect',$event,$t('基金'),'#678F9E')">
          {{ $t('基金') }}
        </div>
        <div class="btn nodeCss" :title="$t('项目')" style="border: 1px solid #95A6CB;background: #95A6CB !important;" @click="startDrag('Rect',$event,$t('项目'),'#95A6CB')">
          {{ $t('项目') }}
        </div>
        <!--
        <div class="btn nodeCss" :title="$t('交易对手')" style="border: 1px solid #ffc800;background: #ffc800 !important;" @mousedown="startDrag('Rect',$event,$t('交易对手'),'#ffc800')">
          this.$t('交易对手')
        </div>
        -->
        <el-dropdown :hide-on-click="false">
          <div class="btn nodeCss" :title="$t('矩形说明')" style="border: 1px solid #5b5b5b; background: #ffffff00 !important" @click="startDrag('Rect',$event,$t('矩形说明'),'#ffffff00')">
            {{ $t('矩形说明') }}
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="startDrag('Circle',$event,$t('圆形说明'),'#ffffff00')">{{ $t('圆形说明') }}</el-dropdown-item>
            <el-dropdown-item @click.native="startDrag('Polygon',$event,$t('条件说明'),'#ffffff00')">{{ $t('条件说明') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="btn-group">
        <el-tooltip placement="bottom">
          <div slot="content">{{ $t('撤销(ctrl+z)') }}<br>{{ $t('重做(ctrl+u)') }})<br>{{ $t('复制(ctrl+c)') }}<br>{{ $t('粘贴(ctrl+v)') }}<br>{{ $t('删除(delete)') }}</div>
          <div :class=" ['btn', 'currentArrow']" style="margin-top: 5px;" @click="revoke()">
            <i class="iconfont icon-jiantou" />
          </div>
        </el-tooltip>
      </div>
      <div class="btn-group">
        <el-tooltip v-hasPermi="['deal:dealArchitectureDiagram:remove']" :content="deleteNodeMsg" placement="bottom">
          <div class="btn" style="margin-top: 5px;" @click="deleteNode()">
            <i class="iconfont icon-shanchu" />
          </div>
        </el-tooltip>
        <el-tooltip v-hasPermi="['deal:dealArchitectureDiagram:edit']" :content="$t('保存至本地')" placement="bottom">
          <div class="btn" :title="$t('保存')" style="margin-top: 5px;" @click="saveToPNG()">
            <i class="iconfont icon-baocun" />
          </div>
        </el-tooltip>
      </div>
      <div class="btn nodeCss">
        <el-button v-hasPermi="['deal:dealArchitectureDiagram:edit']" type="primary" style="margin-right: 2px" @keydown.meta.83.native="saveNode" @click="saveNode">
          {{ $t('保存') }}
        </el-button>
      </div>
      <div class="btn" style="margin-right: -25px;height: 100%;line-height: 2.4;margin-left: 10px;cursor: pointer;">
        <el-tooltip :content="$t('是否展示缩略图')" placement="bottom">
          <i class="el-icon-d-arrow-right" @click="isShowMiniMap = !isShowMiniMap" />
        </el-tooltip>
      </div>
    </div>
    <!-- mino小地图 -->
    <div v-show="isShowMiniMap" id="containerCHartMini" style="width: 150px;height: 80px;position: absolute;right: 280px;" />

  </div>
</template>
<script>
import '@antv/x6-vue-shape'
import { Graph, Shape, FunctionExt, DataUri } from '@antv/x6'
import RightDrawer from './RightDrawer'
import insertCss from 'insert-css'
import { startDragToGraph } from './methods.js'
import { saveAssetInvestmentStructure, getByDealId } from '@/api/deal/estate/dealArchitectureDiagram/dealArchitectureDiagram'

var data = {}
export default {
  components: {
    RightDrawer
  },
  data() {
    return {
      history: Graph.HistoryManager,
      title: undefined,
      loading: false,
      graph: undefined,
      type: 'grid',
      selectCell: undefined,
      connectEdgeType: { // 连线方式
        connector: 'normal',
        router: {
          name: 'manhattan'
        }
      },
      form: {
        id: undefined,
        dealId: this.$route.query.id,
        datas: undefined,
        remark: undefined,
        delFlag: undefined,
        imageContext: undefined
      },
      grid: { // 网格设置
        size: 20, // 网格大小 10px
        visible: true, // 渲染网格背景
        type: 'mesh',
        args: {
          color: '#fff',
          thickness: 1, // 网格线宽度/网格点大小
          factor: 10
        }
      },
      // 点击删除时的提示
      deleteNodeMsg: this.$t('删除'),
      // 是否展示小地图
      isShowMiniMap: false
    }
  },
  created() {
    this.init()
  },
  mounted() {
    this.initX6()
  },
  methods: {
    // 页面初始化
    init() {
      this.loading = true
      getByDealId(this.$route.query.id).then(response => {
        if (response.data !== undefined && response.data !== null && response.data !== '') {
          this.form = response.data
          this.graph.fromJSON(JSON.parse(response.data.datas))
        }
        this.loading = false
      })
    },
    // 保存节点信息
    saveNode() {
      const nodes = this.graph.getNodes()
      const edges = this.graph.getEdges()
      data = {
        nodes: nodes,
        edges: edges
      }
      this.loading = true
      this.form.datas = JSON.stringify(data)
      this.graph.toPNG((dataUri) => {
        this.form.remark = dataUri
        this.form.column2 = '2'
        saveAssetInvestmentStructure(this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess(this.$t('保存成功'))
          } else {
            this.msgError(response.msg)
          }
          this.loading = false
        })
      }, {
        backgroundColor: 'white',
        padding: {
          top: 50,
          right: 50,
          bottom: 50,
          left: 50
        },
        quality: 1,
        copyStyles: false
      })
    },
    initX6() {
      var _that = this
      this.graph = new Graph({
        // 小地图
        minimap: {
          enabled: true,
          container: document.getElementById('containerCHartMini'),
          height: 80,
          width: 150
        },
        // 撤销/重做
        history: {
         enabled: true
        },
        // 滚动
        scroller: {
          enabled: true,
          pannable: true,
          pageBreak: true,
          pageVisible: true
        },
        container: document.getElementById('containerChart'),
        width: 1700,
        height: 800,
        grid: _that.grid,
        resizing: { // 调整节点宽高
          enabled: true,
          orthogonal: false
        },
        selecting: true, // 可选
        snapline: true,
        interacting: {
          edgeLabelMovable: true
        },
        connecting: { // 节点连接
          anchor: 'center',
          connectionPoint: 'anchor',
          allowBlank: false,
          snap: true,
          createEdge() {
            return new Shape.Edge({
              attrs: {
                line: {
                  stroke: '#1890ff',
                  strokeWidth: 1,
                  targetMarker: {
                    name: 'classic',
                    size: 8
                  },
                  strokeDasharray: 0, // 虚线
                  style: {
                    animation: 'ant-line 30s infinite linear'
                  }
                }
              },
              label: {
                text: ''
              },
              connector: _that.connectEdgeType.connector,
              router: {
                name: _that.connectEdgeType.router.name || ''
              },
              zIndex: 0
            })
          }
        },
        highlighting: {
          magnetAvailable: {
            name: 'stroke',
            args: {
              padding: 4,
              attrs: {
                strokeWidth: 4,
                stroke: '#6a6c8a'
              }
            }
          }
        },
        // 剪切板
        clipboard: {
          enabled: true,
          useLocalStorage: true
        },
        // 快捷键
        keyboard: {
          enabled: true,
          global: true,
          format(key) {
            return key
              .replace(/\s/g, '')
              .replace('cmd', 'command')
          }
        }
      })
      // 快捷键配置
      this.graph.bindKey(['mate+v', 'command+v', 'ctrl+v'], () => {
        if (!this.graph.isClipboardEmpty()) {
          console.log('粘贴')
          const cells = this.graph.paste({ offset: 32 })
          this.graph.cleanSelection()
          this.graph.select(cells)
        }
        return false
      })
      this.graph.bindKey(['mate+c', 'command+c', 'ctrl+c'], () => {
        const cell = this.graph.getSelectedCells()
        if (cell && cell.length > 0) {
          this.graph.copy(cell)
          console.log('复制', cell)
        }
        return false
      })
      // 删除
      this.graph.bindKey(['delete', 'BackSpace'], () => {
          this.$nextTick(() => {
            this.deleteNode()
          })
      })
      // 撤销
      this.graph.bindKey(['mate+z', 'command+z', 'ctrl+z'], () => {
        this.$nextTick(() => {
          this.history.undo()
        })
      })
      // 重做
      this.graph.bindKey(['mate+u', 'command+u', 'ctrl+u'], () => {
        this.$nextTick(() => {
          this.history.redo()
        })
      })
      // 初始化撤销功能
      this.history = this.graph.history
      //
      insertCss(`
        @keyframes ant-line {
          to {
              stroke-dashoffset: -1000
          }
        }
      `)
      this.graph.fromJSON(data)
      // 鼠标移入移出节点
      this.graph.on('node:mouseenter', FunctionExt.debounce(() => {
          const container = document.getElementById('containerChart')
          const ports = container.querySelectorAll(
            '.x6-port-body'
          )
          this.showPorts(ports, true)
        }),
        500
      )
      this.graph.on('node:mouseleave', () => {
        const container = document.getElementById('containerChart')
        const ports = container.querySelectorAll(
          '.x6-port-body'
        )
        this.showPorts(ports, false)
      })
      this.graph.on('blank:click', () => {
        this.type = 'grid'
      })
      this.graph.on('cell:click', ({ cell }) => {
        this.type = cell.isNode() ? 'node' : 'edge'
      })
      // 双击节点时间
      this.graph.on('node:dblclick', ({ e, x, y, cell, view }) => {
        console.log({ e, x, y, cell, view })
      })
      this.graph.on('selection:changed', (args) => {
        args.added.forEach(cell => {
          this.selectCell = cell
          if (cell.isEdge()) {
            cell.isEdge() && cell.attr('line/strokeDasharray', 5) // 虚线蚂蚁线
            cell.addTools([
              {
                name: 'vertices',
                args: {
                  padding: 4,
                  attrs: {
                    strokeWidth: 0.1,
                    stroke: '#2d8cf0',
                    fill: '#ffffff'
                  }
                }
              }
            ])
          }
        })
        args.removed.forEach(cell => {
          cell.isEdge() && cell.attr('line/strokeDasharray', 0) // 正常线
          cell.removeTools()
        })
      })
    },
    showPorts(ports, show) {
      for (let i = 0, len = ports.length; i < len; i = i + 1) {
        ports[i].style.visibility = show ? 'visible' : 'hidden'
      }
    },
    // 拖拽生成正方形或者圆形
    startDrag(type, e, text, color) {
      startDragToGraph(this.graph, type, e, text, color)
    },
    // 删除节点
    deleteNode() {
      this.deleteNodeMsg = this.$t('删除')
      const cell = this.graph.getSelectedCells()
      if (cell && cell.length > 0) {
        this.graph.removeCells(cell)
        this.type = 'grid'
      } else {
        this.deleteNodeMsg = this.$t('请先选择一个节点')
        setTimeout(() => {
          this.deleteNodeMsg = this.$t('删除')
        }, 1500)
      }
    },
    // 保存png
    saveToPNG() {
      console.log(this.graph)
      var that = this
      this.$prompt(this.$t('下载名称'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        inputPlaceholder: that.$t('架构图.png')
      }).then(({ value }) => {
        that.$nextTick(() => {
          that.graph.toPNG((dataUri) => {
            // 下载
            DataUri.downloadDataUri(dataUri, (value === undefined || value === '' || value === null) ? '架构图.png' : (value + '.png'))
          }, {
            backgroundColor: 'white',
            padding: {
              top: 50,
              right: 50,
              bottom: 50,
              left: 50
            },
            quality: 1,
            copyStyles: false
          })
        })
      }).catch(() => {
      })
    },
    // 撤销
    revoke() {
      this.history.undo()
    }
  }
}
</script>
<style scoped>
@import './iconfont.css';
@import './index.css';

.nodeCss {
  width: 75px !important;
  height: 38px !important;
  line-height: 38px !important;
  font-size: 14px !important;
  color: #000000 !important;
  text-align: center;
  margin-left: 20px;
}

#containerChart {
  margin-top: 80px;
}
</style>
